<template>
<div class="container">
    <div class="card">
        <el-breadcrumb separator="/" class="card-body">
            <el-breadcrumb-item :to="{ path: '/AdminHome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/UserManagement' }">系统用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{ this.$route.meta.title }}</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div class="card">
        <div class="card-header">填写用户信息</div>
        <div class="card-body">
            <div class="avatar-uploader d-flex">
                <label for="name" class="el-form-item__label" style="width: 100px;">上传照片</label>
                <el-upload :action="this.$api.uploadheadphoto" :headers="headers" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <p>注：上传头像提供尺寸500x500像素，<br>电子照片，jpg或png格式，大小不超过1024k</p>
            </div>
            <el-form :model="userForm" ref="userForm" :rules="rules" label-width="100px">
                <div class="info-userForm">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="userForm.name" placeholder="姓名与身份证一致"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-select v-model="userForm.sex" placeholder="请选择性别">
                            <el-option label="男" value="0"></el-option>
                            <el-option label="女" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="密级" prop="secretLevel">
                        <el-select v-model="userForm.secretLevel" placeholder="请选择密级">
                            <el-option label="绝密" value="0"></el-option>
                            <el-option label="秘密" value="1"></el-option>
                            <el-option label="普通" value="2"></el-option>
                            <el-option label="公开" value="3"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="身份证号码" prop="identityNo">
                        <el-input v-model="userForm.identityNo" placeholder="中国公民身份证号码"></el-input>
                    </el-form-item>
                    <el-form-item label="房间号" prop="roomId">
                        <el-input v-model="userForm.roomId" type="number" placeholder="请输入房间号,例如 3-1001"></el-input>
                    </el-form-item>
                    <el-form-item label="工位号" prop="jobNo">
                        <el-input v-model="userForm.jobNo" type="number" placeholder="请输入工位号"></el-input>
                    </el-form-item>
                    <el-form-item label="工位电话" prop="jobMobile">
                        <el-input v-model="userForm.jobMobile" maxlength="11" type="number" placeholder="工位电话号码"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userForm.email" placeholder="请输入联系邮箱"></el-input>
                    </el-form-item>
                    <el-form-item label="所属部门">
                        <el-input v-model="department" maxlength="0" placeholder="点击 '查找' 选择部门" ref="userFind"></el-input>
                        <el-button type="text" size="medium" class="el-query-tree" @click="$tree('查找组织','userFind')">查找</el-button>
                    </el-form-item>
                    <el-form-item label="职位" prop="position">
                        <el-input v-model="userForm.position" placeholder="请输入职位"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" v-model="userForm.remark"></el-input>
                    </el-form-item>
                </div>

                <hr>
                <div class="info-userForm">
                    <el-form-item label="登录账号" prop="account">
                        <el-input v-model.trim="userForm.account" maxlength="18"></el-input>
                    </el-form-item>
                    <input v-model="userForm.password" hidden>
                    <p class="initial-pwd" title="初始密码用于第一次激活,务必记住,忘记需要找管理员进行重置.">
                        初始密码为: <strong class="color-danger">{{userForm.password | formatNubmer}}</strong>
                    </p>
                </div>
                <hr>
                <div class="authorization-list">
                    <el-form-item label="权限分配">
                        <el-tree ref="tree" :data="AuthorizationList" show-checkbox node-key="id" :default-expanded-keys="['1', '2']" :props="defaultProps" @check-change="handleCheckChange" class="authList">
                        </el-tree>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('userForm')">立即创建</el-button>
                    <el-button @click="resetForm('userForm')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</div>
</template>

<script>
import md5 from "js-md5";
import { getToken } from "@/utils/auth.js";
import request from "@/utils/request";
export default {
  name: "UserCreate",
  data() {
    return {
      AuthorizationList: [],
      userForm: {
        headPhotoUrl: "",
        name: "",
        sex: "",
        secretLevel: "",
        identityNo: "",
        jobNo: "",
        jobMobile: "",
        roomId:"",
        email: "",
        department: {
          id: "",
          label: ""
        },
        position: "",
        remark: "",

        account: "",
        password: "",

        permissonIdList: []
      },
      rules: {
        name: [
          { required: true, message: "请输入用户姓名", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        secretLevel: [
          { required: true, message: "请选择密级", trigger: "change" }
        ],
        identityNo: [
          { required: true, message: "请输入身份证", trigger: "blur" },
          {
            min: 12,
            max: 18,
            message: "请输入18位中国公民身份证号码",
            trigger: "blur"
          }
        ],
        jobNo: [
          { required: true, message: "请输入工位号", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" }
        ],
        roomId: [
          { required: true, message: "请输入房间号", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" }
        ],
        jobMobile: [
          { required: false, message: "请输入手机号", trigger: "blur" },
          {
            min: 8,
            max: 11,
            message: "长度在 8 到 11 位工位号码",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 8, max: 64, message: "请输入正确邮箱格式", trigger: "blur" }
        ],
        department: [
          { required: true, message: "请选择部门", trigger: "blur" }
        ],
        position: [
          { required: true, message: "请输入职位", trigger: "blur" },
          { min: 2, max: 18, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ],
        account: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 18, message: "长度在 2 到 18 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 2, max: 18, message: "长度在 2 到 18 个字符", trigger: "blur" }
        ]
      },
      headers: {
        Authorization: getToken()
      },
      defaultProps: {
        children: "children",
        label: "meunName"
      },
      imageUrl: ""
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let userData = this.userForm;
          request({
            url: this.$api.createUser,
            method: "post",
            data: userData
          }).then(res => {
            if (res.code === "000000") {
              this.$message.success("创建新用户成功");
              setTimeout(() => {
                this.resetForm("userForm");
              }, 500);
            }
          });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleAvatarSuccess(res, file) {
      if (res.code !== "000000") {
        this.$message.error("上传头像错误,请重试!");
      } else {
        console.log(res);
        this.imageUrl = URL.createObjectURL(file.raw);
        // this.imageUrl = res.data;
        console.log(URL.createObjectURL(file.raw));
        this.userForm.headPhotoUrl = res.data;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      } else if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
    handleNodeClick(data) {
      console.log(data);
    },
    getRadomCode() {
      let randomCode = [];
      for (var i = 0; i <= 5; i++) {
        let code = parseInt(Math.random() * 10);
        randomCode.push(code);
      }
      return randomCode.join("");
    },
    getAllPermisson() {
      request({
        url: this.$api.getAllPermisson,
        method: "get"
      }).then(res => {
        this.AuthorizationList = res.data;
      });
    },
    handleCheckChange(data, checked, indeterminate) {
      // console.log(data, checked);
      let id = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());
      let checkData = [];
      for (let val of id) {
        checkData.push({
          id: val
        });
      }
      this.userForm.permissonIdList = checkData;
    }
  },
  mounted() {
    this.userForm.password = this.getRadomCode();
    //初始化权限列表
    this.getAllPermisson();
  },
  filters: {
    formatNubmer: function(n) {
      return n.slice(0, 3) + " " + n.slice(3, 6);
    }
  },
  computed: {
    //注册树形菜单数据
    department: function() {
      if (this.$store.getters.treeData.ref !== "userFind") {
        return this.userForm.department.label;
      } else {
        this.userForm.department.label = this.$store.getters.treeData.val;
        this.userForm.department.id = this.$store.getters.treeData.id;
        return this.$store.getters.treeData.val;
      }
    }
  }
};
</script>
<style scoped>
.info-userForm {
  width: 420px;
  position: relative;
}

.authList {
  border: 1px solid #f2f2f2;
  padding: 0.5rem 1rem;
  width: 420px;
}

.el-query-tree {
  position: absolute;
  right: -40px;
  top: 0;
}

.authorization-list {
  width: 60%;
}

.initial-pwd {
  margin-left: 100px;
  margin-top: 5px;
  margin-bottom: 10px;
  border: 1px dashed #ddd;
  padding: 10px;
  text-align: center;
  border-radius: 4px;
}
</style>